package org.opens.config;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class ExceptionHandlerPage implements UrlBlockHandler {

    /**
     * 说明:
     * <pre>
     *     1. BlockException e是5中规则的验证失败时抛出的异常的父类.
     * </pre>
     */
    @Override
    public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException e) throws IOException {
        ResponseData result = null;

        if (e instanceof FlowException) {
            result = new ResponseData(-1, "接口限流异常");
        } else if (e instanceof DegradeException) {
            result = new ResponseData(-2, "接口降级异常");
        } else if (e instanceof AuthorityException) {
            result = new ResponseData(-3, "接口被授权规则限制");
        } else if (e instanceof SystemBlockException) {
            result = new ResponseData(-4, "接口被系统规则限制");
        } else if (e instanceof ParamFlowException) {
            result = new ResponseData(-5, "接口参数限流异常");
        }

        if (result != null) {
            // 解决中文乱码
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSON.toJSONString(result));
        }
    }

}

@Data
@NoArgsConstructor
@AllArgsConstructor
class ResponseData {

    private Integer code;

    private String message;

}